package com.itgone.easyblog.service.image.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.itgone.easyblog.config.BlogServiceException;
import com.itgone.easyblog.service.image.IFileUploadService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.*;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class QnyFileService implements IFileUploadService {

    private static final String ACCESS_KEY = "i7cnAGM8REbosqWM02le89KilGLN_0O5wUeRD4ns";

    private static final String SECRET_KEY = "vpKJ5498M4en2P4-T-Khsq4U8JlYJEONq63vgFUa";

    private static final String BUCKET_NAME = "earlman";

    private static final String SERVER_BASE_URL = "http://qiniu.oss.itgone.com/";

    @Override
    public String upload(MultipartFile uploadFile) {
        // 生成文件名
        String newFileName = getRandomName(uploadFile.getOriginalFilename());
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            String upToken = auth.uploadToken(BUCKET_NAME);
            System.out.println(upToken);
            long start = System.currentTimeMillis();
            Response response = uploadManager.put(uploadFile.getInputStream(), newFileName, upToken, null, null);
            long end = System.currentTimeMillis();
            System.out.println(end - start);
            //解析上传成功的结果
            DefaultPutRet putRet = JSONUtil.toBean(response.bodyString(), DefaultPutRet.class);
            return SERVER_BASE_URL + putRet.key;
        } catch (Exception ex) {
            StaticLog.error("文件上传失败", ex);
            throw new BlogServiceException("文件上传失败");
        }
    }

    @Override
    public int deleteByUrl(String url) {
        //设置需要操作的账号的AK和SK
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

        RegionGroup regionGroup = new RegionGroup();
        regionGroup.addRegion(Region.huanan());
//        regionGroup.addRegion(Region.region1());
        Configuration cfg = new Configuration(regionGroup);

        //实例化一个BucketManager对象
        BucketManager bucketManager = new BucketManager(auth, cfg);
        //要测试的空间和key，并且这个key在你空间中存在
        try {
            //调用delete方法移动文件
            String key = FileUtil.getName(url);
            bucketManager.delete(BUCKET_NAME, key);
        } catch (QiniuException e) {
            //捕获异常信息
            Response r = e.response;
            StaticLog.error("文件删除失败，message is {}", r.toString());
            return 0;
        }
        return 1;
    }

    private String getRandomName(String originalFilename) {
        String mainName = FileUtil.mainName(originalFilename);
        String uuid = UUID.fastUUID().toString(true);
        return originalFilename.replace(mainName, uuid);
    }
}
